//
//  HomeViewController.swift
//  ifanr
//
//  Created by 😱😱 on 16/9/13.
//  Copyright © 2016年 😱😱. All rights reserved.
//

import UIKit
import Moya
import SwiftyJSON
import FMDB



class HomeViewController: BasePageViewController {
    enum RefreshType {
        case RefreshTypePull// 下拉加载
        case RefreshTypePush// 上拉加载
        case RefreshTypeNormal// 第一次进入加载
    }
    // MARK: - LifeCycle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.redColor()
        
        tableView.delegate = self
        tableView.dataSource = self
        pullToRefresh.delegate = self
        loadDataWithRefreshType(RefreshType.RefreshTypeNormal, page: 1)
    }
    
    // MARK: load data
    /**
     加载数据
     1、先从数据库取
     2、有12条，如果是普通、上拉（上拉其实也要发请求，考虑到更新十分慢，先不刷）则显示，如果是下拉刷新，则要发请求，
     3、如果小于12条，直接根据page、发请求
     */
    private func loadDataWithRefreshType(refreshType: RefreshType, page: Int) {
        let content = StatusHelper.homeStatusWithPage(page)
        if content.count < 12 || refreshType == RefreshType.RefreshTypePull{
            ifanrProvider.request(APIConstant.Home_latest(page)) { (result) in
                switch result {
                case let .Failure(Error):
                    print(Error)
                    self.showTips("没得网迈？", duration: 2)
                    self.isRefreshing = false
                    self.pullToRefresh.endRefresh()
                case let .Success(response):
                    let json = JSON(data:response.data)
                    if let content = json["data"].array{
                        // 缓存
                        switch refreshType {
                        case .RefreshTypePull:// 下拉
                            if self.pubdateFirst.length == 0 {// 表明第一次加载
                                StatusHelper.saveStatus(json["data"].array!)
                                self.pubdateLast = content.last!["post_modified"].stringValue
                            } else {// 表明，下拉刷新
                                for status in content {
                                    if status["post_modified"].stringValue == self.pubdateFirst {
                                        break
                                    }
                                    StatusHelper.saveStatus([status])
                                }
                            }
                        case .RefreshTypePush:// 上拉
                            for status in content {
                                if status["post_modified"].stringValue > self.pubdateLast {
                                    continue
                                }
                                StatusHelper.saveStatus([status])
                            }
                        default:
                            StatusHelper.saveStatus(json["data"].array!)
                            self.pubdateLast = content.last!["post_modified"].stringValue
                            self.pubdateFirst = content.first!["post_modified"].stringValue
                        }
                        
                        //异步处理Array，转成HomeCellFrameModel
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
                            let frameArray: Array<HomeCellFrameModel> = content.map({ (dict) -> HomeCellFrameModel in
                                return HomeCellFrameModel(model: HomeStatusModel(dict: dict.dictionaryObject!))
                            })
                            
                            dispatch_async(dispatch_get_main_queue(), {
                                switch refreshType {
                                case .RefreshTypePull:
                                    if self.pubdateFirst.length == 0 {
                                        frameArray.forEach{
                                            self.latestCellLayout.append($0)
                                        }
                                    } else {
                                        for cellModel in frameArray {
                                            var i = 0
                                            if cellModel.model.post_modified == self.pubdateFirst {
                                                if i == 0 {
                                                    self.showTips("没得多的新闻了，等到更新", duration: 2)
                                                }
                                                break
                                            }
                                            self.latestCellLayout.insert(cellModel, atIndex:0)
                                            i += 1
                                        }
                                    }
                                    self.pubdateFirst = frameArray[0].model.post_modified
                                case .RefreshTypePush:
                                    for cellModel in frameArray {
                                        if cellModel.model.post_modified > self.pubdateLast {
                                            continue
                                        }
                                        self.latestCellLayout.append(cellModel)
                                    }
                                    self.lastPage += 1
                                default:
                                    frameArray.forEach{
                                        self.latestCellLayout.append($0)
                                    }
                                }
                                self.tableView.reloadData()
                                self.isRefreshing = false
                                self.pullToRefresh.endRefresh()
                            })
                        })
                    } else {
                        print("数据出错了")
                        self.isRefreshing = false
                        self.pullToRefresh.endRefresh()
                    }
                }
            }
        } else {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
                let frameArray: Array<HomeCellFrameModel> = content.map({ (dict) -> HomeCellFrameModel in
                    return HomeCellFrameModel(model: HomeStatusModel(dict: dict as! NSDictionary))
                })
                
                dispatch_async(dispatch_get_main_queue(), {
                    self.pubdateFirst = frameArray[0].model.post_modified
                    self.pubdateLast = frameArray.last!.model.post_modified
                    
                    switch refreshType {// 从数据库中取了12条数据
                    case .RefreshTypeNormal:
                        frameArray.forEach{
                            self.latestCellLayout.append($0)
                        }
                    case .RefreshTypePull:// 下拉加载，要放到数组最前面
                        for cellModel in frameArray {
                            var i = 0
                            self.latestCellLayout.insert(cellModel, atIndex: i)
                            i += 1
                        }
                    case .RefreshTypePush:
                        frameArray.forEach{
                            self.latestCellLayout.append($0)
                        }
                        self.lastPage += 1
                    }
                    self.tableView.reloadData()
                    self.isRefreshing = false
                    self.pullToRefresh.endRefresh()
                })
            })
        }
    }
    
    //MARK: getter - setter
    lazy var ifanrProvider = MoyaProvider<APIConstant>()
    // 列表数据
    private var latestCellLayout = Array<HomeCellFrameModel>()
    
    var pubdateLast: String = ""
    var pubdateFirst: String = ""
    var lastPage = 2
}

// MARK: - tableView代理
extension HomeViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return latestCellLayout.count
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        let cellModel = latestCellLayout[indexPath.row].model
        if cellModel.post_type == PostType.dasheng {
            let cell = cell as! HomeTextCell
            cell.popularLayout = latestCellLayout[indexPath.row]
        } else if cellModel.post_type == PostType.data {
            let cell = cell as! HomeDataCell
            cell.popularLayout = latestCellLayout[indexPath.row]
        } else {
            let cell = cell as! HomeImageCell
            cell.popularLayout = latestCellLayout[indexPath.row]
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cellModel = latestCellLayout[indexPath.row].model
        var cell : UITableViewCell!
        if cellModel.post_type == PostType.dasheng {
            cell = HomeTextCell.cellWithTableView(tableView)
        } else if cellModel.post_type == PostType.data {
            cell = HomeDataCell.cellWithTableView(tableView)
        } else {
            cell = HomeImageCell.cellWithTableView(tableView)
        }
        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return latestCellLayout[indexPath.row].cellHeight
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if let model: HomeStatusModel = latestCellLayout[indexPath.row].model {
            let ifDetailsController = IFDetailViewController(model: model, naviTitle: "首页")
            self.navigationController?.pushViewController(ifDetailsController, animated: true)
        }
    }
}

// MARK: - 下拉刷新回调
extension HomeViewController: PullToRefreshDelegate {
    func pullToRefreshViewDidRefresh(pulllToRefreshView: PullToRefreshView) {
        loadDataWithRefreshType(RefreshType.RefreshTypePull, page: 1)
    }
}

// MARK: - 上拉加载更多
extension HomeViewController {
    override func scrollViewDidScroll(scrollView: UIScrollView) {
        super.scrollViewDidScroll(scrollView)
        if differY < happenY {
            if !isRefreshing {
                isRefreshing = true
                loadDataWithRefreshType(RefreshType.RefreshTypePush, page: self.lastPage)
                print(self.lastPage)
            }
        }
    }
}
